package com.fire.common.incepter;

import com.fire.common.domain.BusinessException;
import com.fire.common.domain.CommonErrorCode;
import com.fire.common.domain.ErrorCode;
import com.fire.common.domain.RestErrorResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author fire
 * @date 2021年07月16日17:17
 */

@ControllerAdvice //与ExceptionHandler配合使用实现全局异常处理
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
//    捕获异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse processException(HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest,Exception e){
//        异常处理
        /**
         * 系统自定义异常，直接取出errCode和errMessage
         */
        if( e instanceof BusinessException){
            logger.info(e.getMessage(),e);
//            解析系统自定义异常
            BusinessException business = (BusinessException) e;
            ErrorCode errorCode = business.getErrorCode();
//            错误代码
            int code = errorCode.getCode();
//            错误信息
            String message = errorCode.getDesc();
            return new RestErrorResponse(String.valueOf(code),message);
        }
//       不是系统i自定义异常  code:999999   message:系统未知错误
        logger.error("系统异常",e);
        return new RestErrorResponse(String.valueOf(CommonErrorCode.UNKNOWN.getCode()), CommonErrorCode.UNKNOWN.getDesc());

    }
}
